package net

import (
	"net"
	"rpc-demo/net/exception"
)

type NexusClient[T any] struct {
	Address string
	Rhd     readHandler[T]
	Sr      string
	chanel  *NexusChanel[T]
}

func (client *NexusClient[T]) createConn() error {
	conn, err := net.Dial(TYPE, client.Address)
	if err != nil {
		return err
	}
	client.chanel = &NexusChanel[T]{
		conn: conn,
		sr:   getSr[T](client.Sr),
	}
	client.handleRead()
	return nil
}

func (client *NexusClient[T]) handleRead() {
	go client.chanel.handleRead(client.Rhd)
}

func (client *NexusClient[T]) SendMsg(data T) error {
	if client.chanel == nil {
		err := client.createConn()
		if err != nil {
			return err
		}
	}
	return client.chanel.Write(data)
}

func (client *NexusClient[T]) Close() error {
	if client.chanel == nil {
		return &exception.RpcError{Err: "connection already close"}
	} else {
		return client.chanel.Close()
	}
}
